//
//  ShoppingCartListCtr.swift
//  smosky
//
//  Created by zhuxietong on 2018/6/28.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import Eelay
import soapp


public enum CartStatus
{
    case normal
    case eidt
}

public class ShoppingCartListCtr: ListController {
    
    public var status:CartStatus = .normal
    {
        didSet{
            refreshStatus()
        }
    }
    
    public var sections:TP.section{
        get{
            let sect:TP.section =
                [
                    [
                    ],
                    []
                    //                SandBox.section(count: 8)
            ]
            return sect
        }
    }
    
    public let selector:TP.selector = [
        "<section1>":GoodsItemCell.self,
        "cellID<seller>":SellerCell.self
    ]
    
    let bottomBar = SubmitBar()
    let topBar = TopBar()
    
    var height_c = NSLayoutConstraint()
    
    let bar = UIView()
    
    public override func layTable(tableView: UIView) {
//        bottomBar.controller = self
//                super.layTable(tableView: tableView)
        
        jo_contentView.eelay = [
            [tableView,[ee.L.R],[bottomBar,ee.T,ee.B]],
            [bottomBar,[ee.L.R],[ee.B.safe]],
            [topBar,[ee.L.R],[tableView,ee.T,ee.B]],
        ]
        height_c = NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: jo_contentView, attribute: .top, multiplier: 1, constant: (TP.topHeight))
        jo_contentView.addConstraint(height_c)
        
    }
    
    public override func mo_change_localizable(obj: Any?) {
        self.title = "购物车".loc
        refreshStatus()
        mo_request_send()
    }
    public override func viewDidLoad() {
//        self.automaticallyAdjustsScrollViewInsets = false
//        if #available(iOS 11.0, *) {
//                  self.tableView.contentInsetAdjustmentBehavior = .never
//              } else {
//                  self.automaticallyAdjustsScrollViewInsets = false
//              }
//
        
        super.viewDidLoad()
        self.title = "购物车".loc
        tableView.buildDynamicHeight(height: 78)
        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = UIColor._tableBackground
        
        tableView.clipsToBounds = true
        topBar.deleteBt.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        mo_request_send()
        
        bottomBar.confirmBt.addTarget(self, action: #selector(commitAction), for: .touchUpInside)
        //        self.status = .normal
        
        editBt.ui.font(font: UIFont.systemFont(ofSize: 16)).ncolor(color: ._foreground).ntitle(title: "管理".loc)
        editBt.addTarget(self, action: #selector(toggle), for: .touchUpInside)
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editBt)
        
        weak var wself = self
        __notice.add(task: (Goods.Notice.goodsCartChage,{_ in
            wself?.mo_request_send()
        }))
        __notice.add(task: (JoUser.Notice.login,{_ in
                 wself?.mo_request_send()
             }))
        __notice.add(task: (JoUser.Notice.logout,{_ in
                 wself?.mo_request_send()
             }))
     
        
    }
    
    @objc public func commitAction() {
        let list = self.selectedList.0
        let ids = list.map { (dict) -> String in
            return dict["id",""]
        }
        if ids.count < 1
        {
            "请选择要够买的商品".loc.alert()
            return
        }
        let ctr = SCOrderSubmitCtr()
        ctr.buyType = .cartGoods(ids)
        self.navigationController?.pushViewController(ctr, animated: true)
        //        print(ids)
        
    }
    
    let editBt = UIButton()
    
    override public func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    var cartList:NSMutableArray = NSMutableArray()
    {
        didSet{
            editBt.alpha = 1
            if cartList.count < 1
            {
                loadingV.show(message: __app.welcome_qote, title: "您的购物车是空的".loc)
                editBt.alpha = 0
                return
            }
            tableView.load(sections: sections, selector: selector)
            tableView.model <-- ("section1",cartList,NodeInsert.arrayRefresh)
            tableView.reloadData()
            
        }
    }
    
    override public func mo_request_send() {
        loadingV.loading()
        weak var wself = self
        JoTask().get._surl(.我的购物车).log_response().json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            print("----iiiIS",status)
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                }
                if let list = DataNode<NSMutableArray>.path(node: "list", obj)
                {
                    wself?.cartList = ShoppingCartListCtr.dealList(list: list)
                    return
                }
            }
            if(status == .unAuth){
                wself?.mo_tip_login()
                return
            }
            wself?.mo_request_alert()
            }.run()
    }
    
    static func dealList(list:NSMutableArray) -> NSMutableArray {
        let newList = NSMutableArray()
        list.list { (obj:NSMutableDictionary, i) in
            let carts = DataNode.path(node: "carts", obj, value: NSMutableArray())
            var itemIDs = [String]()
            carts.list({ (one:NSMutableDictionary, i) in
                itemIDs.append(one["id",""])
            })
            
            let seller = obj
            seller["cellID"] = "seller"
            seller["carts"] = itemIDs.mutable_array
            carts.insert(seller, at: 0)
            newList.addObjects(from: carts as! [Any])
        }
        return newList
    }
    
    
    
    override public func mo_detail_reload() {
        bottomBar.mo.model = mo.detail
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editBt)

    }
    
    
    
    override public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case "changeNum","changeSelected":
            bottomBar.mo.model = model
        case "deleteInvalidItem":
            delelteIDs(ids: [model["id",""]])
        default:
            break
        }
    }
    
    
    
}

extension ShoppingCartListCtr{
    class TopBar:JoView
    {
        override func mo_change_localizable(obj: Any?) {
            let f = UIFont.systemFont(ofSize: 12)
            _ = deleteBt.ui.ncolor(hex: "#fff").ntitle(title: "删除".loc).font(font: f).set(radius: 12, width: 1, color: .white)
            _ = titleL.ui.font14.cl_fff.text("极速清理".loc)
        }
        let titleL = UILabel()
        let deleteBt = UIButton()
        override func addLayoutRules() {
            self.backgroundColor = ___shop.tint
            eelay = [
                [titleL,[ee.L.Y,[AppTheme.edge,0]],100],
                [deleteBt,[ee.R.Y,[-AppTheme.edge,0]]],
            ]
            let f = UIFont.systemFont(ofSize: 12)
            _ = deleteBt.ui.ncolor(hex: "#fff").ntitle(title: "删除".loc).font(font: f).set(radius: 12, width: 1, color: .white)
            _ = titleL.ui.font14.cl_fff.text("极速清理".loc)
            deleteBt.contentEdgeInsets = [5,14]

        }
        override var intrinsicContentSize: CGSize{
            get{
                return [Swidth,40]
            }
        }
    }
    
}

extension ShoppingCartListCtr{
    
    
    var list:NSMutableArray{
        get{
            let ls = DataNode.path(node: "section1", tableView.model, value: NSMutableArray())
            return ls
        }
    }
    var selectedList:([NSMutableDictionary],[IndexPath]){
        get{
            var ls1 = [NSMutableDictionary]()
            var ls2 = [IndexPath]()
            
            
            list.list { (dict:NSMutableDictionary, i) in
                if dict[FK.selected,"0"] == "1"
                {
                    //                    print("===pppp==|\(dict["__row__",""])")
                    ls1.append(dict)
                    ls2.append(IndexPath(row:i, section: 1))
                }
            }
            return (ls1,ls2)
        }
    }
    
    func removeSeller(deleteGoodsIDs:[String])->([NSMutableDictionary],[IndexPath]){
        var ls1 = [NSMutableDictionary]()
        var ls2 = [IndexPath]()
        
        let tablelist = list
        tablelist.list { (cellItem:NSMutableDictionary, i) in
            if cellItem["cellID",""] == "seller"
            {
                let carts = DataNode.path(node: "carts", cellItem, value: NSMutableArray())
                var deleteItems = [String]()
                carts.list({ (ID:String, i) in
                    if deleteGoodsIDs.contains(ID)
                    {
                        print("containt+|\(ID)")
                        
                        deleteItems.append(ID)
                    }
                })
                
                
                deleteItems.forEach({ (one) in
                    carts.remove(one)
                })
                
                if carts.count < 1
                {
                    ls1.append(cellItem)
                    ls2.append(IndexPath(row:i, section: 1))
                }
            }
        }
        tablelist.removeObjects(in: ls1)
        tableView.deleteRows(at: ls2, with: .fade)
        return (ls1,ls2)
        
    }
    
    @objc func deleteAction() {
        
        let listObjs = self.selectedList.0
        let ids = listObjs.map { (dict) -> String in
            return dict["id",""]
        }
        
        if ids.count < 1
        {
            "请选择要移除的商品".loc.alert()
            return
        }
        
        weak var wself = self
        JoAlertView(info: "提示".loc,"是否确认移除购物车?".loc,"取消".loc).append(title: "移除".loc, style: .destructive) {
            wself?.delelteIDs(ids: ids)
            }.show(at: self)
        
        
    }
    
    func delelteIDs(ids:[String]) {
        weak var wself = self
        
        HUD.share.show().mode(.indeterminate)
        JoTask().post.log.params(["ids":ids.joined(separator: ",")])._surl(.移出购物车).json_handle { (status, msg, obj, resp) in
            HUD.share.hide(animated: true)
            if status.isSuccess{
                wself?.mo_request_send()
                //                if let dict = obj as? NSMutableDictionary{
                //                    wself?.bottomBar.mo.model = dict
                //                }
                //
                //                guard let ws = wself else{return}
                //                let ls = ws.selectedList
                //                ws.list.removeObjects(in: ls.0)
                //                ws.tableView.deleteRows(at: ls.1, with: .fade)
                //
                //                _ = ws.removeSeller(deleteGoodsIDs: ids)
                //
                //                ws.editBt.alpha = 1
                //
                //                if ws.list.count < 1
                //                {
                //                    ws.loadingV.show(message: __app.welcome_qote, title: "您的购物车是空的")
                //                    ws.editBt.alpha = 0
                //                    return
                //                }
                return
            }
            msg.alert()
            }.run()
    }
    
    
    
    func refreshStatus() {
        
        var top = TP.topHeight+40
        switch self.status {
        case .eidt:
            
            editBt.setTitle("完成".loc, for: .normal)
            top = TP.topHeight + 40
            
        default:
            editBt.setTitle("管理".loc, for: .normal)
            top = TP.topHeight
        }
        
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.29)
        UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: 7)!)
        height_c.constant = top
        tableView.layoutIfNeeded()
        topBar.layoutIfNeeded()
        jo_contentView.layoutIfNeeded()
        UIView.commitAnimations()
    }
    
    @objc func toggle()  {
        switch self.status {
        case .eidt:
            self.status = .normal
        default:
            self.status = .eidt
        }
        
        
    }
}











